#include "DatabaseWorker.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QCoreApplication>
#include <QThread>

void EcgInsertTask::execute() {
    // 使用唯一的工作线程连接名称
    QString connectionName = QString("WorkerConnection_%1").arg((quintptr)QThread::currentThreadId());
    QSqlDatabase db = QSqlDatabase::database(connectionName);

    if (!db.isValid() || !db.isOpen()) {
        qWarning() << "数据库连接无效或未打开";
        return;
    }

    QSqlQuery query(db);
    query.prepare("INSERT INTO ecg_data (timestamp, subject_id, ch1, ch2, ch3, ch4, ch5, ch6, ch7, ch8) "
                  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    query.addBindValue(m_timestamp);
    query.addBindValue(m_subjectId);

    for (int i = 0; i < 8; i++) {
        if (i < m_data.size()) {
            query.addBindValue(m_data[i]);
        } else {
            query.addBindValue(0.0);
        }
    }

    if (!query.exec()) {
        qWarning() << "插入ECG数据失败:" << query.lastError().text();
    }
}

void EegInsertTask::execute() {
    // 使用唯一的工作线程连接名称
    QString connectionName = QString("WorkerConnection_%1").arg((quintptr)QThread::currentThreadId());
    QSqlDatabase db = QSqlDatabase::database(connectionName);

    if (!db.isValid() || !db.isOpen()) {
        qWarning() << "数据库连接无效或未打开";
        return;
    }

    QSqlQuery query(db);

    // 开始事务
    if (!query.exec("BEGIN TRANSACTION")) {
        qWarning() << "开始事务失败:" << query.lastError().text();
        return;
    }

    // 将处理后的数据写入数据库
    bool success = true;

    // 检查是否有足够的通道数据
    if (m_processedData.size() >= 3 && !m_processedData[0].isEmpty()) {
        int sampleCount = m_processedData[0].size();
        qint64 timestamp = m_timestamp;
        const int timeInterval = 4; // 4ms per sample at 250Hz

        // 遍历所有样本
        for (int i = 0; i < sampleCount; i++) {
            query.prepare("INSERT INTO eeg_data (timestamp, fp1, fpz, fp2, subject_id) VALUES (?, ?, ?, ?, ?)");
            query.addBindValue(timestamp + i * timeInterval);
            query.addBindValue(m_processedData[0][i]); // FP1
            query.addBindValue(m_processedData[1][i]); // FPZ
            query.addBindValue(m_processedData[2][i]); // FP2
            query.addBindValue(m_subjectId);

            if (!query.exec()) {
                qWarning() << "插入EEG数据失败:" << query.lastError().text();
                success = false;
                break;
            }
        }
    } else {
        qWarning() << "处理后的数据不完整，无法写入数据库";
        success = false;
    }

    // 提交或回滚事务
    if (success) {
        if (!query.exec("COMMIT")) {
            qWarning() << "提交EEG数据事务失败:" << query.lastError().text();
            query.exec("ROLLBACK");
        } else {
            qDebug() << "成功写入" << (m_processedData.size() > 0 ? m_processedData[0].size() : 0) << "个EEG数据点到数据库";
        }
    } else {
        query.exec("ROLLBACK");
    }
}

DatabaseWorker::DatabaseWorker(QObject *parent) : QObject(parent), m_abort(false) {
    // 构造函数中不创建数据库连接
    // 连接将在process()方法中创建，确保它在正确的线程上初始化
}

DatabaseWorker::~DatabaseWorker() {
    stop();

    // 获取当前线程的连接名称
    QString connectionName = QString("WorkerConnection_%1").arg((quintptr)QThread::currentThreadId());

    // 关闭数据库连接
    {
        QSqlDatabase db = QSqlDatabase::database(connectionName, false);
        if (db.isValid() && db.isOpen()) {
            db.close();
        }
    }

    // 移除数据库连接
    if (QSqlDatabase::contains(connectionName)) {
        QSqlDatabase::removeDatabase(connectionName);
    }
}

void DatabaseWorker::addTask(DatabaseTask* task) {
    QMutexLocker locker(&m_mutex);
    m_tasks.enqueue(task);
    m_condition.wakeOne();
}

void DatabaseWorker::stop() {
    QMutexLocker locker(&m_mutex);
    m_abort = true;
    m_condition.wakeOne();
}

void DatabaseWorker::process() {
    // 为当前线程创建唯一的连接名称
    QString connectionName = QString("WorkerConnection_%1").arg((quintptr)QThread::currentThreadId());

    // 检查连接是否已存在
    if (QSqlDatabase::contains(connectionName)) {
        QSqlDatabase::removeDatabase(connectionName);
    }

    // 在工作线程中创建数据库连接
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", connectionName);
    db.setDatabaseName("physio_data.sqlite");

    if (!db.open()) {
        qWarning() << "无法在工作线程中打开数据库:" << db.lastError().text();
        emit finished();
        return;
    } else {
        qDebug() << "工作线程数据库连接成功打开 (连接名称:" << connectionName << ")";
    }

    forever {
        DatabaseTask* task = nullptr;

        {
            QMutexLocker locker(&m_mutex);
            if (m_tasks.isEmpty() && !m_abort) {
                m_condition.wait(&m_mutex);
            }

            if (m_abort) {
                break;
            }

            if (!m_tasks.isEmpty()) {
                task = m_tasks.dequeue();
            }
        }

        if (task) {
            task->execute();
            delete task;

            // 处理事件循环，保持响应性
            QCoreApplication::processEvents();
        }
    }

    // 清理剩余任务
    QMutexLocker locker(&m_mutex);
    while (!m_tasks.isEmpty()) {
        delete m_tasks.dequeue();
    }

    // 关闭数据库连接
    db.close();

    emit finished();
}
